package com.jzoom.zoom.admin.models;

import com.jzoom.zoom.admin.models.AdminDaoModel.PrimaryKeyAdapter;
import com.jzoom.zoom.cache.annotations.Cache;
import com.jzoom.zoom.cache.annotations.CacheRemove;
import com.jzoom.zoom.common.Destroyable;
import com.jzoom.zoom.common.annotations.Inject;
import com.jzoom.zoom.common.designpattern.SingletonUtils;
import com.jzoom.zoom.common.designpattern.SingletonUtils.SingletonInit;
import com.jzoom.zoom.common.utils.Classes;
import com.jzoom.zoom.dao.Dao;
import com.jzoom.zoom.dao.Record;
import com.jzoom.zoom.dao.adapters.NameAdapter;
import com.jzoom.zoom.dao.driver.DbStructFactory;
import com.jzoom.zoom.dao.meta.TableMeta;
import com.jzoom.zoom.web.exception.StatusException;
import com.jzoom.zoom.web.exception.StatusException.NotFoundException;
import com.jzoom.zoom.web.view.impl.StringView;
import org.apache.commons.lang3.StringUtils;
import org.commonmark.node.Node;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.html.HtmlRenderer;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ContentSercie implements Destroyable {
	@Override
	public void destroy() {
		Classes.destroy(daoMap);
	}


	/**
	 * 表对应的dao
	 */
	private Map<String, AdminDaoModel> daoMap = new ConcurrentHashMap<String, AdminDaoModel>();


	@Inject(value = "admin")
	private Dao admin;

	@Inject
	private DaoService daoService;

	private PrimaryKeyAdapter getDaoId(Dao dao, String table) {
		PrimaryKeyAdapter id;
		try {
			DbStructFactory struct = dao.getDbStructFactory();
			TableMeta meta = struct.getTableMeta(dao.ar(), table);
			struct.fill(dao.ar(), meta);
			NameAdapter adapter = dao.getNameAdapterFactory().getNameAdapter(table);
			id = AdminDaoModel.getDaoId(meta, adapter);
		} catch (Exception e) {
			id = AdminDaoModel.createDefault("id");
		}
		return id;
	}


	@Inject
	private DaoListener daoListener;

	@Inject
	private DecorationTableService decorationTableService;

	public AdminDaoModel getDao(String ds, String module) throws NotFoundException {
		if (StringUtils.isEmpty(module)) {
			throw new RuntimeException("ModuleId is null");
		}

		if (StringUtils.isEmpty(ds)) {
			throw new RuntimeException("ds is null");
		}

		final String fixedDs = ds.toLowerCase();

		module = module.toLowerCase();


		final Dao dao = daoService.getDao(fixedDs);
		final String table = module;
		String key = new StringBuilder().append(ds).append(":").append(module).toString();

		return SingletonUtils.liteDoubleLockMap(daoMap, key, new SingletonInit<AdminDaoModel>() {

			@Override
			public AdminDaoModel create() {
				AdminDaoModel baseDao = new AdminDaoModel(fixedDs, table, getDaoId(dao, table));
				baseDao.setDao(dao);
				baseDao.setDaoListener(daoListener);
				baseDao.setDecorationTableService(decorationTableService);
				return baseDao;
			}
		});
	}

	private StringView renderPage(Record record) {
		return new StringView(record.getString("template"));
	}

	/**
	 * 模板页面
	 * 
	 * @param content
	 * @return
	 */
	private String renderH5(String content) {
		return content;
	}

	/**
	 * 原始的
	 * 
	 * @param content
	 * @return
	 */
	private String renderRaw(String content) {
		return content;
	}

	/**
	 * markdown
	 * 
	 * @param content
	 * @return
	 */
	private String renderMd(String content) {
		Parser parser = Parser.builder().build();
		Node document = parser.parse(content);
		HtmlRenderer renderer = HtmlRenderer.builder().build();
		return renderer.render(document);
	}

	/**
	 * 修改内容
	 */
	@CacheRemove(format = "page:%s:%s")
	public void updatePage(String module, String method) {

	}

	/**
	 *
	 * @param module
	 * @param method
	 * @return
	 * @throws NotFoundException
	 */
	@Cache(format = "page:%s:%s")
	public StringView createPage(String module, String method) throws NotFoundException {
		if ("/edit".equals(method) || "/add".equals(method)) {
			List<Record> records = admin.table("sys_page").where("url", module + "/add")
					.orWhere("url", module + "/edit").find();
			if (records == null || records.isEmpty()) {
				throw new StatusException.NotFoundException();
			}
			if (records.size() > 1) {
				// 找到对应的视图
				for (Record record : records) {
					if (record.getString("url").contains(method)) {
						return renderPage(record);
					}
				}
			}
			return renderPage(records.get(0));
		}

		Record record = admin.table("sys_page").where("url", module + method).get();
		if (record == null) {
			throw new StatusException.NotFoundException();
		}
		return renderPage(record);
	}

	public void updatePageForUrl(String url) {
		String[] parts = url.split("/");
		if(parts.length >= 2) {
			String module = parts.length == 3 ? parts[0] + "/" + parts[1] : parts[0];
			String method = "/"+parts[parts.length-1];
			if("/edit".equals(method) || "/add".equals(method)) {
				updatePage(module, "/add");
				updatePage(module, "/edit");
			}else {
				updatePage(module, method);
			}
		}
	}

}
